<template>
  <div class="employee-container">
    <head-tool>
      <div slot="after">
        <el-button
          type="warning"
          size="small"
          @click="$router.push({ path: '/import', query: { type: 'emp' } })"
          >导入</el-button
        >
        <el-button type="danger" size="small" @click="exportExcel"
          >导出</el-button
        >
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="addEmp"
          >新增员工</el-button
        >
      </div>
    </head-tool>
    <el-card class="content-box">
      <el-table border :data="employeeData" v-loading="loading">
        <el-table-column label="序号" width="100px">
          <template slot-scope="scope">
            {{ scope.$index + (pageInfo.page - 1) * pageInfo.size + 1 }}
          </template>
        </el-table-column>

        <el-table-column label="姓名" sortable prop="username" width="180px">
          <template slot-scope="{ row }">
            <img
              v-imgerror="defalutPhoto"
              :src="row.staffPhoto"
              class="user-avatar"
              @click="showQrCode(row.staffPhoto)"
            />
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="工号"
          sortable
          prop="workNumber"
          width="180px"
        ></el-table-column>
        <el-table-column
          label="聘用形式"
          sortable
          prop="formOfEmployment"
          width="180px"
        >
          <template slot-scope="{ row }">
            {{ row.formOfEmployment | hireType }}
          </template>
        </el-table-column>
        <el-table-column
          label="部门"
          sortable
          prop="departmentName"
          width="180px"
        ></el-table-column>
        <el-table-column
          label="入职时间"
          sortable
          prop="timeOfEntry"
          width="180px"
        >
          <template slot-scope="{ row }">
            {{ row.timeOfEntry | formatDate }}
          </template></el-table-column
        >
        <el-table-column
          label="转正时间"
          sortable
          prop="correctionTime"
          width="180px"
        >
          <template slot-scope="{ row }">
            {{ row.correctionTime | formatDate }}
          </template></el-table-column
        >
        <el-table-column
          label="账户状态"
          sortable
          prop="enableState"
          width="180px"
        >
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.enableState"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch> </template
        ></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          min-width="280px"
          ><template slot-scope="{ row }">
            <el-button
              type="text"
              size="small"
              @click="
                $router.push({
                  path: '/employees/detail',
                  query: { id: row.id },
                })
              "
              >查看</el-button
            >
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="showRole(row.id)"
              >角色</el-button
            >
            <el-button type="text" size="small" @click="delEmp(row.id)"
              >删除</el-button
            >
          </template></el-table-column
        >
      </el-table>
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          :current-page.sync="pageInfo.page"
          @current-change="getEmployeeList"
          :page-size="pageInfo.size"
          layout="total, prev, pager, next"
          :total="pageInfo.total"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <add-emp :showDialog.sync="showDialog"></add-emp>
    <el-dialog :visible.sync="showCodeDialog" title="二维码">
      <!-- 二维码 -->
      <el-row type="flex" justify="center">
        <canvas ref="canvas"></canvas>
      </el-row>
    </el-dialog>
    <role-setting
      ref="roleSet"
      :showRoleDialog.sync="showRoleDialog"
      :userId="currentId"
    />
  </div>
</template>

<script>
import { getEmployeeList, delEmp } from "@/api/employees";
import constant from "@/api/constant/employees";
import addEmp from "./component/add-emp.vue";
import roleSetting from "./component/role-setting.vue";
import { formatDate } from "@/filters";
import QrCode from "qrcode";
export default {
  components: { addEmp, roleSetting },
  name: "employees",
  data() {
    return {
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      currentId: "",
      defalutPhoto: require("@/assets/common/bigUserHeader.png"),
      employeeData: [],
      pageInfo: {
        page: 1,
        size: 10,
        total: 0,
      },
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    addEmp() {
      this.showDialog = true;
    },
    async showRole(id) {
      this.currentId = id;
      this.showRoleDialog = true;
      await this.$refs.roleSet.getUserProfile(id);
    },
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true;
        // 为true的时候还没有渲染DOM，所以意味着里面还没有canvas标签
        // 那么所以需要等dom渲染了再来找canvas标签，并把他画成二维码
        // 用一个回调：nextTick:下次dom更新调用
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.canvas, url);
        });
      } else {
        this.$$message.warning("该员工没有图片！");
      }
    },
    async getEmployeeList() {
      this.loading = true;

      let res = await getEmployeeList(this.pageInfo);
      this.employeeData = res.data.rows;
      this.employeeData.forEach((item) => {
        item.enableState = item.enableState == 1 ? true : false;
      });
      this.pageInfo.total = res.data.total;
      this.loading = false;
    },
    async delEmp(id) {
      try {
        await this.$confirm("你确定要删除该员工吗？", "提示", {
          type: "warning",
        });

        await delEmp(id);
        this.$message.success("删除员工成功");

        if (this.employeeData.length == 1 && this.pageInfo.page != 1) {
          this.pageInfo.page--;
        }

        this.getEmployeeList();
      } catch {
        console.log(error);
      }
    },
    // 导出excel数据
    // 导出的事件
    async exportExcel() {
      // 请求所有的员工数据
      let res = await getEmployeeList({
        page: 1,
        size: this.pageInfo.total,
      });

      let list = res.data.rows;

      const headers = {
        手机号: "mobile",
        姓名: "username",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };

      let keys = Object.keys(headers);

      // 对list进行遍历还要得到一个大数组
      let bigArr = list.map((item) => {
        // item是每个元素，又是一个对象，要遍历转成数组
        let arr = [];
        for (let key in headers) {
          // 先根据中文的key，取出对应英文的key
          let engKey = headers[key];
          if (key == "入职日期" || key == "转正日期") {
            let res = formatDate(item[engKey]);
            arr.push(res);
          } else if (key == "聘用形式") {
            let str = item[engKey] == 1 ? "正式" : "未知";
            arr.push(str);
          } else {
            arr.push(item[engKey]);
          }
        }
        return arr;
      });

      // 懒加载使用插件的办法
      // 哪里要用，就在哪里导入插件对应的js
      // 导入成功就调用.then
      import("@/vendor/Export2Excel").then((excel) => {
        // 这个插件里写了这个方法才能用
        excel.export_json_to_excel({
          // 表头
          header: keys, //表头 必填
          // 数据
          data: bigArr,
          filename: "员工列表",
        });
      });
    },

    exportHardExcel() {
      import("@/vendor/Export2Excel").then((excel) => {
        // 这个插件里写了这个方法才能用
        excel.export_json_to_excel({
          // 表头
          header: [
            "姓名",
            "手机号",
            "入职日期",
            "聘用形式",
            "转正日期",
            "工号",
            "部门",
          ], //表头 必填
          // 数据
          data: [["111", "23232", "323123", "1", "32312", "3231", "aaaa"]],
          filename: "员工列表",
          multiHeader: [["姓名", "主要信息", "", "", "", "", "部门"]],
          merges: ["A1:A2", "B1:F1", "G1:G2"],
        });
      });
    },
  },
  filters: {
    hireType(val) {
      let list = constant.hireType.filter((item) => item.id == val);
      return list[0] ? list[0].value : "未知";
    },
  },
};
</script>

<style lang="scss">
.employee-container {
  .content-box {
    margin: 0 20px;
    .el-table {
      th {
        background-color: #fafafa !important;
      }
    }
  }
  .user-avatar {
    cursor: pointer;
    height: 30px;
    border-radius: 15px;
    vertical-align: middle;
  }
}
</style>